/* Project 7 Virtual Machine
   CS 2110
   Members: Brad Klingensmith,
	Matt Sparkman, Abdullah Alosayef,
	Sherm Newsome */
#include <stdio.h>
#include "parser.h"

int main()
{
	struct TokenList token_list = New_TokenList();
	struct Token *token;
	int compiled = 1;
	struct VirtualMachineState virtual_machine;
	FILE *file;
	char file_name[100];

	printf("Enter the file load: ");
	scanf("%100s", file_name);

	file = fopen(file_name, "r");
	if (!file)
	{
		fprintf(stderr, "Could not open the file\n");
		return 0;
	}
	/* Check for more tokens */
	while (Has_More_Tokens(file))
	{
		/* Read in the token */
		token = Read_Token(file, stderr);

		/* Check to see if it's valid */
		if (Is_Valid_Token(token))
		{
			/* Print it out and add it to the list */
			Print_Token(token, stdout);
			Add_Token(&token_list, token);
		}
		else
		{
			/* Mark that the code didn't compile so that 
			   it doesn't get executed */
			compiled = 0;
		}
	}

	/* If the code didn't compile, free the 
	   list of tokens and exit without running the code */
	if (!compiled)
	{
		Free_TokenList(&token_list);
		return 0;
	}

	/* Initialize the virtual machine */	
	virtual_machine = Create_Virtual_Machine();

	/* Build an instruction set from the list of tokens */
	if (!Create_Instruction_Set(&virtual_machine, token_list, stderr))
	{
		Free_TokenList(&token_list);
		Free_VirtualMachine(&virtual_machine);
		return 0;
	}


	/* Execute the code */
	Execute_Code(&virtual_machine);

	/* Delete the list */
	Free_TokenList(&token_list);

	/* Clean up the virtual machine */
	Free_VirtualMachine(&virtual_machine);

	/* Exit */
	return 0;
}